package com.ymf.twitter.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.log4j.Logger;

import com.ymf.twitter.hbase.RelationsDAO;
import com.ymf.twitter.hbase.TwitsDAO;
import com.ymf.twitter.hbase.UsersDAO;
import com.ymf.twitter.model.Twit;
import com.ymf.twitter.model.User;

public class IndexAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(IndexAction.class);
	List<String> follows;
	RelationsDAO relationsDao;
	List<Twit> twits;
	
	TwitsDAO twitsDao;
	List<String> unfollows;
	UsersDAO userDao;
	
	public IndexAction(){
		userDao = new UsersDAO(new HTablePool(HBaseConfiguration.create(), 10));
		twitsDao = new TwitsDAO(new HTablePool(HBaseConfiguration.create(), 10));
		relationsDao = new RelationsDAO(new HTablePool(HBaseConfiguration.create(), 10));
		follows = new ArrayList<String>();
		unfollows = new ArrayList<String>();
		twits = new ArrayList<Twit>();
	}

	public String execute() throws Exception{
		if(login_user.equals("")){
			return SUCCESS;
		}
		follows = relationsDao.listFollowsId(login_user);
		List<User> all = userDao.getUsers();
		
		for (User user : all) {
			if(!follows.contains(user.user))
				unfollows.add(user.user);
		}
		unfollows.remove(login_user);
		
		twits.addAll(twitsDao.list(login_user));
		
		for (String user : follows) {
			twits.addAll(twitsDao.list(user));
		}
		
		log.info(String.format("follow.size(): %s \t unfollow.size(): %s \t twits.size():%s", follows.size(), unfollows.size(),twits.size()));
		return SUCCESS;
	}


	public void setTwits(List<Twit> twits) {
		this.twits = twits;
	}

	public List<Twit> getTwits() {
		return twits;
	}

	public List<String> getFollows() {
		return follows;
	}

	public void setFollows(List<String> follows) {
		this.follows = follows;
	}

	public List<String> getUnfollows() {
		return unfollows;
	}

	public void setUnfollows(List<String> unfollows) {
		this.unfollows = unfollows;
	}
		
}